#include<stdio.h>
#include<assert.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>

#define SIZE 100

typedef struct MyFile_
{
    int _fd;
    char buff[SIZE];
    int end;
}MyFile;

MyFile* fopen_(const char* pathName, const char* mode)      //可以加上const修饰
{
    assert(pathName);
    assert(mode);
    MyFile* fp = NULL;
    int fd = 0;
    fp = (MyFile*)malloc(sizeof(MyFile));
    if(fp == NULL)
    {
        perror("malloc");
        return NULL;
    }
    memset(fp, 0, sizeof(MyFile));
    if(*mode == 'w')
    {
        fd = open(pathName, O_WRONLY | O_TRUNC | O_CREAT, 0666);
        fp->_fd = fd; 
    }
    else if(strcmp(mode, "w+") == 0)
    {

    }
    else if(strcmp(mode, "r") == 0)
    {

    }
    else if(strcmp(mode, "r+") == 0)
    {

    }
    else if(strcmp(mode, "a") == 0)
    {

    }
    else if(strcmp(mode, "a+") == 0)
    {

    }
    else 
    {
        printf("bug?\n");
        free(fp);
        fp = NULL;
    }
    return fp;
}

void fputs_(const char* s, MyFile* fp)
{
    assert(s);
    assert(fp);
    strcpy(fp->buff + fp->end, s);
    fp->end += strlen(s);
    if(fp->buff[fp->end - 1] == '\n')
    {
        //printf("%s",fp->buff);
        write(fp->_fd, fp->buff,fp->end);
        //syncfs(fp->_fd);      //此语句可以不用
        fp->end = 0;
    }
}

void fflush_(MyFile* fp)
{
    assert(fp);
    if(fp->end != 0)
    {
        write(fp->_fd, fp->buff, fp->end);
        syncfs(fp->_fd);
        fp->end = 0;
    }
}

void fclose_(MyFile* fp)
{
    assert(fp);
    fflush_(fp);
    close(fp->_fd);
    free(fp);
    fp = NULL;
}

int main()
{
    MyFile* fp = fopen_("log.txt", "w");
    char* s = "snowdragon writed";
    fputs_(s, fp);
    
    //char* s1 = "snowdragon writed, one";
    //fputs_(s1, fp);
    //char* s2 = "snowdragon writed, two\n";  //MyFile中的缓冲区大小需要设置好，如果太小，执行这些语句时会出错
    //fputs_(s2, fp);
    //char* s3 = "snowdragon writed, three";
    //fputs_(s3, fp);
    
    fork();

    fclose_(fp);
    return 0;
}
